package com.bailong.nanny.filter;

import com.bailong.nanny.entity.Admin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter({"/allUser.do","/users.jsp/navigation.jsp"})
public class LoginFilter implements Filter {
    private static final String[] EXCLUSIVE_URL={"code.do","index.jsp","login.do","png",".jpg",".js",".css"};
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        //如果遇到不拦截的URL就直接放行
        for (String str : EXCLUSIVE_URL){
            if(request.getRequestURL().toString().endsWith(str)){
                System.out.println("URL放行：" + request.getRequestURL());
                filterChain.doFilter(req,resp);
                return;
            }
        }
        if(admin!=null){
            System.out.println("放行：" + request.getRequestURL());
            filterChain.doFilter(req,resp);
            return;
        }else{
            System.out.println("拦截：" + request.getRequestURL());
            response.sendRedirect("index.jsp");
        }


    }

    @Override
    public void destroy() {

    }
}
